package com.xiaoxie.util;


import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import sun.misc.Resource;

import java.io.IOException;
import java.io.InputStream;

/**
 * mybaits的工具类
 */
public class MybatisUtils {
    private static SqlSessionFactory sqlSessionFactory;

    /*静态初始化*/
    static{
        String resource = "mybatis-config.xml";
        try {
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 获取SqlSession连接, 这里重载方法
    public static SqlSession getSession(){
        return getSession(true);    // 事务自动提交
    }

    private static SqlSession getSession(boolean b) {
        return sqlSessionFactory.openSession(b);
    }
}
